package com.jvxb.manage.livable.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jvxb.manage.livable.entity.SysPermission;
import com.jvxb.manage.livable.service.SysPermissionService;
import com.jvxb.manage.livable.vo.SysPermissionVo;
import com.jvxb.common.utils.BeanUtil;
import com.jvxb.common.utils.CommonUtil;
import com.jvxb.common.utils.TreeUtil;
import com.jvxb.common.web.RespMsg;
import com.jvxb.modules.configuration.security.SecurityUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * <p>
 * 系统权限表 前端控制器
 * </p>
 *
 * @author jvxb
 * @since 2020-06-07
 */
@RestController
@RequestMapping("/admin/v1/sysPermission")
public class SysPermissionController {

    @Autowired
    private SysPermissionService permissionService;

    @PostMapping(value = {"add"})
    public RespMsg<SysPermission> add(@RequestBody SysPermission sysPermission) {
        if (sysPermission.getPermId() == null) {
            sysPermission.setCreateTime(new Date());
        }
        sysPermission.setPermPid(sysPermission.getPermPid() == -1 ? null : sysPermission.getPermPid());
        permissionService.save(sysPermission);
        return RespMsg.ok(sysPermission);
    }

    @PostMapping("delete")
    public RespMsg<SysPermission> delete(@RequestBody SysPermission sysPermission) {
        permissionService.removeById(sysPermission);
        return RespMsg.ok();
    }

    @GetMapping("getUserPermission")
    public RespMsg<List<SysPermission>> getUserPermission() {
        Long userId = SecurityUtil.currentUserId();
        List<SysPermission> permList = permissionService.getPermissionBySysUserId(userId);
        if (permList == null || permList.size() == 0) {
            return null;
        }
        // 将权限转为树结构，以此构建左侧的权限菜单
        permList = SysPermission.makeTree(permList);
        // 权限树按sort排序,sort小的排在前面。
        Collections.sort(permList);
        return RespMsg.ok(permList);
    }

    @GetMapping("one")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "权限id", dataType = "Integer")
    })
    public RespMsg<SysPermissionVo> one(@RequestParam Integer permId) {
        SysPermission sysPermission = permissionService.getOne(new QueryWrapper<SysPermission>().eq(SysPermission.PERM_ID, permId)
                .select("perm_id, perm_name, perm_desc, perm_pid, perm_url, sort, is_show, create_time".split(", ")));
        SysPermissionVo permissionVo = new SysPermissionVo();
        BeanUtil.copy(sysPermission, permissionVo);
        String parentName = null;
        if (CommonUtil.notNullOrEmpty(sysPermission.getPermPid())) {
            SysPermission parent = permissionService.getOne(new QueryWrapper<SysPermission>().eq(SysPermission.PERM_ID, sysPermission.getPermPid())
                    .select("perm_name"));
            parentName = Optional.ofNullable(parent).map(SysPermission::getPermName).orElseGet(null);
        }
        permissionVo.setParentName(parentName);
        return RespMsg.ok(permissionVo);
    }

    /**
     * 获取权限列表页数据
     */
    @GetMapping("/getPermissionByParentId")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pid", value = "父节点id", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "size", value = "每页条数，默认10条", dataType = "Integer", required = false),
            @ApiImplicitParam(name = "current", value = "第几页,默认第一页", dataType = "Integer", required = false)
    })
    public RespMsg<IPage<SysPermission>> sysPermissionByParentId(@RequestParam(defaultValue = "10") Integer size,
                                                                 @RequestParam(defaultValue = "1") Integer current,
                                                                 Integer pid) {
        IPage<SysPermission> page = permissionService.getPermissionByParentId(pid, current, size);
        return RespMsg.ok(page);
    }

    /**
     * 获取权限列表树数据(全量)
     */
    @GetMapping("/getPermissionTree")
    @ResponseBody
    public RespMsg<List> sysPermissionTree() {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.select("perm_id,create_time,is_show,perm_desc,perm_name,perm_pid,perm_url,sort".split(","));
        List<SysPermission> permList = permissionService.list(wrapper);
        if (CommonUtil.notNullOrEmpty(permList)) {
            final List<Map> permMapList = CommonUtil.getList();
            permList.stream().forEach(e -> {
                permMapList.add(CommonUtil.getMap("id", e.getPermId(), "parentId", e.getPermPid(), "label", e.getPermName()));
            });
            return RespMsg.ok(TreeUtil.makeTree(permMapList));
        }
        return RespMsg.ok(permList);
    }

    @PostMapping(value = {"update"})
    public RespMsg<SysPermission> update(@RequestBody SysPermissionVo sysPermissionVo) {
        SysPermission permission = new SysPermission();
        BeanUtil.copy(sysPermissionVo, permission);
        permission.setPermPid(permission.getPermPid() == -1 ? null : permission.getPermPid());
        permissionService.updateById(permission);
        return RespMsg.ok(permission);
    }
}

